<template>
	<n-modal
		v-model:show="showModal"
		:title="title"
		preset="dialog"
		:show-icon="false"
		:mask-closable="false"
		style="width: 520px"
		@close="handleClose"
	>
		<n-form
			ref="formRef"
			require-mark-placement="left"
			:model="formValue"
			:rules="rules"
			label-align="left"
			label-placement="left"
			:label-width="160"
			:size="size"
			:style="{
				maxWidth: '640px'
			}"
		>
			<n-form-item>
				<div class="box">
					<span class="mr-1"></span>
					邀请码信息
				</div>
			</n-form-item>

			<div class="flex items-center">
				<n-form-item label="邀请码有效期：" path="termOfValidity">
					<n-checkbox
						v-model:checked="termOfValidityCheck"
						@update:checked="handleTermOfValidityCheck"
					>
						不限
					</n-checkbox>
					<n-date-picker
						v-show="!isTermOfValidityDisabled"
						v-model:value="formValue.termOfValidity"
						:disabled="isTermOfValidityDisabled"
						type="daterange"
						clearable
						@update:value="handleTermOfValidityChange"
					/>
				</n-form-item>
			</div>
			<div class="flex items-center">
				<n-form-item label="邀请码使用次数：" path="maxUse">
					<n-checkbox v-model:checked="maxUseCheck" @update:checked="handleMaxUseCheck">
						不限
					</n-checkbox>
					<n-input-number
						v-show="!isMaxUseDisabled"
						v-model:value="formValue.maxUse"
						style="width: 244px"
						:disabled="isMaxUseDisabled"
						:min="0"
						placeholder="请输入"
					/>
				</n-form-item>
			</div>

			<n-form-item>
				<div class="box">
					<span class="mr-1"></span>
					福利信息
				</div>
			</n-form-item>

			<n-form-item label="福利形式：">赠送素材资源</n-form-item>
			<n-form-item label="福利周期：" path="cycleType">
				<n-radio-group
					v-model:value="formValue.cycleType"
					:disabled="isCycleTypeDisabled"
					name="cycleType"
				>
					<n-space>
						<n-radio v-for="(item, index) in cycleType" :key="index" :value="item.value">
							{{ item.label }}
						</n-radio>
					</n-space>
				</n-radio-group>
			</n-form-item>
			<n-form-item label="赠送次数：" path="download">
				<n-input-number
					v-model:value="formValue.download"
					:disabled="isDownloadDisabled"
					style="width: 302px"
					:min="0"
					placeholder="请输入福利次数"
				/>
			</n-form-item>

			<n-form-item label="合作方：">
				<n-radio-group
					v-model:value="formValue.partnerType"
					name="partnerType"
					@change="handlePartnerTypeChange"
				>
					<n-space>
						<n-radio :value="1">内部员工</n-radio>
						<n-radio :value="2">其他机构</n-radio>
					</n-space>
				</n-radio-group>
			</n-form-item>
			<n-form-item
				v-show="formValue.partnerType"
				label=" "
				path="partnerName"
				:show-require-mark="false"
			>
				<n-select
					v-show="formValue.partnerType === 1"
					v-model:value="formValue.partnerName"
					filterable
					placeholder="请输入并选择员工名字"
					:options="generalOptions"
					:loading="generalLoading"
					clearable
					remote
					@search="handleGeneralSearch"
				/>
				<n-input
					v-show="formValue.partnerType === 2"
					v-model:value="formValue.partnerName"
					placeholder="请输入机构名称"
				></n-input>
			</n-form-item>

			<div class="flex justify-end">
				<n-button
					color="rgba(0, 0, 0, 0.1)"
					text-color="#333333"
					class="close_btn"
					@click="handleClose"
				>
					取消
				</n-button>
				<n-button color="#1D6FE9" text-color="#fff" class="confirm_btn ml-1" @click="handleConfirm">
					确认
				</n-button>
			</div>
		</n-form>
	</n-modal>
</template>

<script setup>
import moment from 'moment';
import { ref, reactive, watch, nextTick } from 'vue';
import { useMessage } from 'naive-ui';
// 导入API接口
import { addEditInvitationCode, getPartnerList, getDetail } from '@/api/invitationCodeManage';
// API接口
const props = defineProps({
	modal: Boolean,
	detailId: {
		type: Number,
		default: 0
	},
	title: {
		type: String,
		default: ''
	},
	updateType: {
		type: Number,
		default: null
	}
});

const emit = defineEmits(['update:modal', 'reload']);
const showModal = ref(props.modal);

const qrcode = ref(null);
// 操作关闭
const handleClose = () => {
	showModal.value = false;
	initData();
	emit('update:modal', showModal.value);
};
// 初始化
const initData = () => {
	formValue.cycleType = null;
	formValue.download = null;
	formValue.endTime = null;
	formValue.id = null;
	formValue.maxUse = null;
	formValue.partnerName = null;
	formValue.partnerType = 1;
	formValue.startTime = null;
	formValue.type = 1;
	formValue.termOfValidity = null;
	isTermOfValidityDisabled.value = false;
	termOfValidityCheck.value = false;
	isMaxUseDisabled.value = false;
	maxUseCheck.value = false;
	isCycleTypeDisabled.value = false;
	isDownloadDisabled.value = false;
	formRef.value = null;
};
// 选择有效期
const isTermOfValidityDisabled = ref(false);
const termOfValidityCheck = ref(false);
const handleTermOfValidityChange = (e) => {
	if (e) {
		formValue.startTime = moment(e[0]).format('YYYY-MM-DD') + ' 00:00:00';
		formValue.endTime = moment(e[1]).format('YYYY-MM-DD') + ' 23:59:59';
	} else {
		formValue.startTime = null;
		formValue.endTime = null;
	}
};
const handleTermOfValidityCheck = (e) => {
	if (e) {
		isTermOfValidityDisabled.value = true;
		formValue.startTime = moment(new Date()).format('YYYY-MM-DD') + ' 00:00:00';
		formValue.endTime = '2038-01-19 03:14:07';
		if (formValue.termOfValidity === null) {
			formValue.termOfValidity = [Date.now(), 2147454847000];
		}
	} else {
		isTermOfValidityDisabled.value = false;
		formValue.startTime = null;
		formValue.endTime = null;
		formValue.termOfValidity = null;
	}
};
// 邀请码使用次数
const isMaxUseDisabled = ref(false);
const maxUseCheck = ref(false);
const handleMaxUseCheck = (e) => {
	if (e) {
		isMaxUseDisabled.value = true;
		formValue.maxUse = -999;
	} else {
		isMaxUseDisabled.value = false;
		formValue.maxUse = null;
	}
};
// 员工下拉模糊查询
const generalOptions = ref([]);
const generalLoading = ref(false);
const handleGeneralSearch = (query) => {
	generalLoading.value = true;
	getModalList(query);
	generalLoading.value = false;
};
const formRef = ref(null);
const message = useMessage();
const cycleType = ref([
	{ value: 1, label: '每日' },
	{ value: 2, label: '每周' },
	{ value: 3, label: '每月' },
	{ value: 5, label: '每年' },
	{ value: 9, label: '一次性' }
]);

const formValue = reactive({
	cycleType: null,
	download: null,
	endTime: null,
	id: null,
	maxUse: null,
	partnerName: null,
	partnerType: 1,
	startTime: null,
	type: 1,

	termOfValidity: null
});
const rules = reactive({
	termOfValidity: {
		type: 'array',
		required: true,
		trigger: ['blur', 'change'],
		message: '请选择邀请码有效期'
	},
	maxUse: {
		type: 'number',
		required: true,
		trigger: ['blur'],
		message: '请填写邀请码使用次数'
	},
	cycleType: {
		type: 'number',
		required: true,
		trigger: ['blur'],
		message: '请选择福利周期'
	},
	download: {
		type: 'number',
		required: true,
		trigger: ['blur'],
		message: '请填写福利次数'
	}
});

// 提交表单
const handleConfirm = (e) => {
	formRef.value.validate(async (errors) => {
		if (!errors) {
			let res = null;
			let parmas = JSON.parse(JSON.stringify(formValue));
			parmas.startTime = moment(parmas.startTime).format('YYYY-MM-DD HH:mm:ss');
			parmas.endTime = moment(parmas.endTime).format('YYYY-MM-DD HH:mm:ss');
			delete parmas.termOfValidity;
			res = await addEditInvitationCode(parmas);
			if (res.code === 200) {
				message.success('操作成功');
				handleClose();
				emit('reload');
			} else {
				message.error(res.message);
			}
		}
	});
};
// 福利周期、赠送次数禁用
const isCycleTypeDisabled = ref(false);
const isDownloadDisabled = ref(false);
// 获取编辑详情
const getEditDetail = async (detailId) => {
	const { code, data } = await getDetail({ id: detailId });
	if (code === 200) {
		showModal.value = true;
		formValue.cycleType = data.cycleType;
		formValue.download = data.download;
		formValue.endTime = data.endTime;
		formValue.id = data.id;
		formValue.maxUse = data.maxUse;
		formValue.partnerName = data.partnerName;
		formValue.partnerType = data.partnerType;
		formValue.startTime = data.startTime;
		formValue.type = data.type;
		formValue.termOfValidity = [
			Number(moment(data.startTime).format('x')),
			Number(moment(data.endTime).format('x'))
		];
		if (data.endTime === '2038-01-19 03:14:07') {
			isTermOfValidityDisabled.value = true;
			termOfValidityCheck.value = true;
		}
		if (data.maxUse === -999) {
			isMaxUseDisabled.value = true;
			maxUseCheck.value = true;
		}
		if (data.status === 1) {
			isCycleTypeDisabled.value = true;
			isDownloadDisabled.value = true;
		}
	}
};
// 获取员工列表
const getModalList = async (keywords) => {
	const { code, data } = await getPartnerList({ keywords: keywords });
	if (code === 200) {
		generalOptions.value = data.records.map((item) => {
			return { value: item.userName, label: item.userName };
		});
	}
};
// 合作方选择改变
const handlePartnerTypeChange = () => {
	formValue.partnerName = null;
};
watch(
	() => ({ ...props }),
	(count) => {
		if (count.modal) {
			if (props.updateType === 2) {
				getEditDetail(props.detailId);
			} else {
				showModal.value = count.modal;
			}
			getModalList('');
		}
	}
);
</script>

<style lang="less" scoped>
.ll-qrcode {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 28px;
}
.ll-qrcode-tip {
	text-align: center;
	font-size: 14px;
	color: #333333;
	margin-top: 28px;
}
.box {
	font-size: 14px;
	font-family: PingFangSC-Medium, PingFang SC;
	color: #333333;
	span {
		position: relative;
		top: 1px;
		display: inline-block;
		width: 3px;
		height: 14px;
		background: #57ae59;
	}
}
.close_btn {
	// border: none;
	font-size: 13px;
	font-family: PingFangSC-Regular, PingFang SC;
	// font-weight: 400;
	width: 80px;
	// height: 32px;
	// background: #ddd;
	border-radius: 6px;
}
.confirm_btn {
	// border: none;
	font-size: 13px;
	font-family: PingFangSC-Medium, PingFang SC;
	width: 80px;
	border-radius: 6px;
}

.flex {
	display: -webkit-box;
	display: -ms-flexbox;
	display: -webkit-flex;
	display: flex;
}
.flex-col {
	-webkit-box-orient: vertical;
	-webkit-box-direction: normal;
	-ms-flex-direction: column;
	-webkit-flex-direction: column;
	flex-direction: column;
}
.flex-1 {
	-webkit-box-flex: 1;
	-ms-flex: 1 1 0%;
	-webkit-flex: 1 1 0%;
	flex: 1 1 0%;
}
.flex-wrap {
	-ms-flex-wrap: wrap;
	-webkit-flex-wrap: wrap;
	flex-wrap: wrap;
}
.items-center {
	-webkit-box-align: center;
	-ms-flex-align: center;
	-webkit-align-items: center;
	align-items: center;
}
.justify-between {
	-webkit-box-pack: justify;
	-ms-flex-pack: justify;
	-webkit-justify-content: space-between;
	justify-content: space-between;
}
.justify-end {
	-webkit-box-pack: end;
	-ms-flex-pack: end;
	-webkit-justify-content: flex-end;
	justify-content: flex-end;
}
.mt-1 {
	margin-top: 0.25rem; /* 4px */
}
.mt-2 {
	margin-top: 0.5rem; /* 8px */
}
.ml-1 {
	margin-left: 0.25rem; /* 4px */
}
.mr-1 {
	margin-right: 0.25rem; /* 4px */
}
.mb-2 {
	margin-bottom: 0.5rem; /* 8px */
}
</style>
